package com.yenlien.traceyun.control.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.dao.CompanyModelClassifyDao;
import com.yenlien.traceyun.control.dao.ModelClassifyDao;
import com.yenlien.traceyun.control.entity.CompanyModelClassify;
import com.yenlien.traceyun.control.entity.ModelClassify;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import com.yenlien.traceyun.control.service.rest.AppRestService;
import com.yenlien.traceyun.control.service.rest.FileRestService;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Created by LiuSha on 2020/3/24.
 */
@Service
public class ModelClassifyService {
    @Autowired
    private ModelClassifyDao modelClassifyDao;
    @Autowired
    private FileRestService fileRestService;
    @Autowired
    private JdbcTemplate jdbc;
    @Autowired
    private AppRestService appRestService;

    @Autowired
    private CompanyModelClassifyDao companyModelClassifyDao;

    public List<ModelClassify> findByList(final ModelClassify modelClassify) {
        Pageable pageable = PageRequest.of(modelClassify.getPage(), modelClassify.getPageSize(), Sort.Direction.ASC, "sort");
        return modelClassifyDao.findAll(new Specification<ModelClassify>() {
            @Override
            public Predicate toPredicate(Root<ModelClassify> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> type = root.get("type");
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                list.add(cb.equal(type, 0));
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        });
    }

    public Object findByCompany(String companyId) {
        return modelClassifyDao.findByCompanyId(companyId);
    }

    public Object findByOne(JSONObject object) {
        if (StringUtils.isEmpty(object.getString("userType")) && StringUtils.isEmpty(object.getString("companyId"))) {
            object.put("companyId", UserAuthUtil.getLoginUser().getCompanyId());
            object.put("userType", UserAuthUtil.getLoginUser().getUserType());
        }
        String userType = object.getString("userType");
        List<JSONObject> jsonObjectList = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from t_model_classify where type = 0");
        if (!userType.equals("ADMIN")) {
            JSONObject param = new JSONObject();
            param.put("companyId", object.getString("companyId"));
            param.put("appId", object.getString("appId"));
            List<String> ids = getAppModelIds(param);
            if (ids.size() > 0) {
                String in = "(''";
                for (String id : ids) {
                    in += ",'" + id + "'";
                }
                sql.append(" AND id in " + in + ")");
            }
        }
        sql.append(" ORDER BY sort");
        SqlRowSet rowSet = jdbc.queryForRowSet(sql.toString());
        while (rowSet.next()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", rowSet.getString("id"));
            jsonObject.put("name", rowSet.getString("name"));
            jsonObject.put("displayImg", rowSet.getString("display_img"));
            jsonObject.put("clickImg", rowSet.getString("click_img"));
            jsonObject.put("type", rowSet.getString("type"));
            jsonObjectList.add(jsonObject);
        }
        return jsonObjectList;
    }

    public List<String> getAppModelIds(JSONObject param) {
        JSONObject jsonObject = appRestService.findCompanyCustomAppVersion(param);
        if (jsonObject != null) {
            JSONArray modelIds = jsonObject.getJSONArray("data");
            return JSONObject.parseArray(modelIds.toJSONString(), String.class);
        }
        return new ArrayList<>();
    }

    @Transactional
    public void save(ModelClassify modelClassify, List<MultipartFile> files) throws Exception {
        fileRestService.upload(null, modelClassify, files);
        if (!StringUtils.isEmpty(modelClassify.getParentId())) {
            modelClassify.setParentName(modelClassifyDao.getByName(modelClassify.getParentId()));
            modelClassify.setType(1);
        }
        modelClassifyDao.save(modelClassify);
    }

    @Transactional
    public void update(ModelClassify modelClassify, List<MultipartFile> files) throws Exception {
        fileRestService.upload(modelClassifyDao.findById(modelClassify.getId()), modelClassify, files);
        if (!StringUtils.isEmpty(modelClassify.getParentId())) {
            modelClassify.setParentName(modelClassifyDao.getByName(modelClassify.getParentId()));
            modelClassify.setType(1);
        } else {
            modelClassify.setParentName("");
            modelClassify.setType(0);
        }
        modelClassifyDao.save(modelClassify);
    }

    public Object findByParentId(String parentId) {
        return modelClassifyDao.findByParentId(parentId);
    }

    public Object findById(String id) {
        return modelClassifyDao.findById(id);
    }

    @Transactional
    public void delete(String id, int type) {


        ModelClassify modelClassify = modelClassifyDao.findById(id);
        if (StringUtils.isEmpty(modelClassify.getParentId())) {
            List<CompanyModelClassify> companyModelClassifies = companyModelClassifyDao.findByModelclassifyId(id);
            if (companyModelClassifies != null && companyModelClassifies.size() > 0) {
                throw new BusinessException("500", "已分配用户不能删除");
            }
        } else {
            List<CompanyModelClassify> companyModelClassifies = companyModelClassifyDao.findByModelclassifyId(modelClassify.getParentId());
            if (companyModelClassifies != null && companyModelClassifies.size() > 0) {
                throw new BusinessException("500", "已分配用户不能删除");
            }
        }
        List<ModelClassify> modelClassifies = modelClassifyDao.findByParentId(id);

        if (type == 0) {
            modelClassifyDao.delete(modelClassify);
            modelClassifyDao.deleteAll(modelClassifies);
        } else {
            modelClassifyDao.delete(modelClassify);
            if (modelClassifies.size() > 0) {
                for (ModelClassify model : modelClassifies) {
                    model.setType(0);
                    model.setParentId("");
                    model.setParentName("");
                    modelClassifyDao.save(model);
                }
            }
        }
        companyModelClassifyDao.deleteByModelclassifyId(id);
    }
}
